package com.gitee.huanminabc.utils_tools.log_extend.filter;

import com.gitee.huanminabc.jcommon.base.SnowIdUtil;
import com.gitee.huanminabc.jcommon.str.StringUtil;
import com.gitee.huanminabc.utils_tools.log_extend.Constants;
import com.gitee.huanminabc.utils_tools.log_extend.LogTraceContextHolder;

import javax.servlet.Filter;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;


/**
 * @author 胡安民
 *
 * 日志链路过滤器,从请求头中获取日志链路信息
 */
public class LogTraceFilter implements Filter {


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, javax.servlet.FilterChain filterChain) throws IOException, ServletException {
        try{
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            //先从header中取traceId,如果取不到，在生成
            String traceId = request.getHeader(Constants.LOG_TRACE_ID_HEADER);
            if (StringUtil.isEmpty(traceId)){
                traceId = SnowIdUtil.uniqueLongHex();
            }
            LogTraceContextHolder.set(traceId);
            filterChain.doFilter(servletRequest, servletResponse);
        }finally {
            LogTraceContextHolder.remove();
        }
    }


}
